package cn.xspace.chatui.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;

import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.StringToolkit;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.xspace.chatui.R;


public class ExpressionUtil {
    /**
     * 对spanableString进行正则判断，如果符合要求，则以表情图片代替
     */
    private static void dealExpression(Context context,
                                       SpannableString spannableString, Pattern patten, int start, int size)
            throws Exception {
        if (size == 0) size = 55;
        Matcher matcher = patten.matcher(spannableString);
        while (matcher.find()) {
            String key = matcher.group();
            //Log.d("Key", key);
            key = EmotionHM.get(key);
            if (matcher.start() < start) {
                continue;
            }
            Field field = R.drawable.class.getDeclaredField(key);
            int resId = Integer.parseInt(field.get(null).toString());
            if (resId != 0) {
                Bitmap bitmap = BitmapFactory.decodeResource(
                        context.getResources(), resId);
                bitmap = Bitmap.createScaledBitmap(bitmap, StringToolkit.dip2px(context, size), StringToolkit.dip2px(context, size), true);
                ImageSpan imageSpan = new ImageSpan(bitmap);
                int end = matcher.start() + key.length();
                spannableString.setSpan(imageSpan, matcher.start(), end,
                        Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                if (end < spannableString.length()) {
                    dealExpression(context, spannableString, patten, end, size);
                }
                break;
            }
        }
    }

    public static SpannableString getExpressionString(Context context,
                                                      String str, int size) {
        SpannableString spannableString = new SpannableString(str);
        Pattern sinaPatten = Pattern.compile(ExpressionUtil.zhengze,
                Pattern.CASE_INSENSITIVE); // 通过传入的正则表达式来生成一个pattern
        try {
            dealExpression(context, spannableString, sinaPatten, 0, size);
        } catch (Exception e) {
            Log.e("dealExpression", e.getMessage() + " ");
        }
        return spannableString;
    }

    public static HashMap<String, String> EmotionHM = new HashMap<String, String>();
    public static String zhengze = "";

    static {
        EmotionHM.put("[微笑]", "ewx_");
        EmotionHM.put("[撇嘴]", "epz_");
        EmotionHM.put("[色]", "es_");
        EmotionHM.put("[发呆]", "efd_");
        EmotionHM.put("[得意]", "ede_");
        EmotionHM.put("[流泪]", "ell_");
        EmotionHM.put("[害羞]", "ehx_");
        EmotionHM.put("[闭嘴]", "ebz_");
        EmotionHM.put("[睡]", "ej_");
        EmotionHM.put("[大哭]", "edk_");
        EmotionHM.put("[尴尬]", "egg_");
        EmotionHM.put("[发怒]", "efn_");
        EmotionHM.put("[调皮]", "etp_");
        EmotionHM.put("[呲牙]", "ecy_");
        EmotionHM.put("[惊讶]", "ejy_");
        EmotionHM.put("[难过]", "eng_");
        EmotionHM.put("[酷]", "ek_");
        EmotionHM.put("[冷汗]", "elh_");
        EmotionHM.put("[抓狂]", "ezk_");
        EmotionHM.put("[吐]", "et_");
        EmotionHM.put("[偷笑]", "etx_");
        EmotionHM.put("[愉快]", "eyk_");
        EmotionHM.put("[白眼]", "eby_");
        EmotionHM.put("[傲慢]", "eam_");
        EmotionHM.put("[饥饿]", "eje_");
        EmotionHM.put("[困]", "eu_");
        EmotionHM.put("[惊恐]", "ejk_");
        EmotionHM.put("[流汗]", "ela_");
        EmotionHM.put("[傻笑]", "esx_");
        EmotionHM.put("[悠闲]", "eyx_");
        EmotionHM.put("[傻笑]", "esx_");
        EmotionHM.put("[奋斗]", "eff_");
        EmotionHM.put("[咒骂]", "ezm_");
        EmotionHM.put("[疑问]", "eyw_");
        EmotionHM.put("[嘘]", "ex_");
        EmotionHM.put("[晕]", "ey_");
        EmotionHM.put("[疯了]", "efl_");
        EmotionHM.put("[衰]", "ei_");
        EmotionHM.put("[骷髅]", "ekl_");
        EmotionHM.put("[敲打]", "eqd_");
        EmotionHM.put("[再见]", "ezj_");
        EmotionHM.put("[汗]", "eh_");
        EmotionHM.put("[抠鼻]", "ekb_");
        EmotionHM.put("[鼓掌]", "egz_");
        EmotionHM.put("[糗大了]", "eqdl_");
        EmotionHM.put("[坏笑]", "ehi_");
        EmotionHM.put("[左哼哼]", "ezhh_");
        EmotionHM.put("[右哼哼]", "eyhh_");
        EmotionHM.put("[哈欠]", "ehq_");
        EmotionHM.put("[鄙视]", "ebs_");
        EmotionHM.put("[委屈]", "ewq_");
        EmotionHM.put("[快哭了]", "ekkl_");
        EmotionHM.put("[阴险]", "eyi_");
        EmotionHM.put("[亲亲]", "eqq_");
        EmotionHM.put("[吓]", "eh_");
        EmotionHM.put("[可怜]", "ekk_");
        EmotionHM.put("[菜刀]", "ecd_");
        EmotionHM.put("[西瓜]", "exg_");
        EmotionHM.put("[啤酒]", "epj_");
        EmotionHM.put("[篮球]", "elq_");
        EmotionHM.put("[乒乓]", "epp_");
        EmotionHM.put("[喝茶]", "ehc_");
        EmotionHM.put("[吃饭]", "ecf_");
        EmotionHM.put("[猪头]", "ezt_");
        EmotionHM.put("[献花]", "exh_");
        EmotionHM.put("[凋谢]", "edx_");
        EmotionHM.put("[红唇]", "ehz_");
        EmotionHM.put("[爱心]", "eax_");
        EmotionHM.put("[心碎]", "exs_");
        EmotionHM.put("[蛋糕]", "edg_");
        EmotionHM.put("[闪电]", "esd_");
        EmotionHM.put("[炸弹]", "ezd_");
        EmotionHM.put("[刀]", "ed_");
        Iterator<String> ite = EmotionHM.keySet().iterator();
        StringBuffer sb = new StringBuffer();
        while (ite.hasNext()) {
            String value = ite.next();
            value = value.replace("[", "\\[").replace("]", "\\]");
            sb.append(value).append("|");
        }
        zhengze = sb.toString();
        if (zhengze.length() > 0) {
            zhengze = zhengze.substring(0, zhengze.length() - 1);
        }
    }

    public static String convertToMsg(CharSequence cs, Context mContext) {
        SpannableStringBuilder ssb = new SpannableStringBuilder(cs);
        ImageSpan[] spans = ssb.getSpans(0, cs.length(), ImageSpan.class);
        for (int i = 0; i < spans.length; i++) {
            ImageSpan span = spans[i];
            String c = span.getSource();
            int a = ssb.getSpanStart(span);
            int b = ssb.getSpanEnd(span);
            if (c.contains("[")) {
                ssb.replace(a, b, convertUnicode(c));
            }
        }
        ssb.clearSpans();
        return ssb.toString();
    }


    private static String convertUnicode(String emo) {
        emo = emo.substring(1, emo.length() - 1);
        if (emo.length() < 6) {
            return new String(Character.toChars(Integer.parseInt(emo, 16)));
        }
        String[] emos = emo.split("_");
        char[] char0 = Character.toChars(Integer.parseInt(emos[0], 16));
        char[] char1 = Character.toChars(Integer.parseInt(emos[1], 16));
        char[] emoji = new char[char0.length + char1.length];
        for (int i = 0; i < char0.length; i++) {
            emoji[i] = char0[i];
        }
        for (int i = char0.length; i < emoji.length; i++) {
            emoji[i] = char1[i - char0.length];
        }
        return new String(emoji);
    }


    /**
     * 判断是否有emoji
     *
     * @param str
     * @return
     */
    public static boolean containsEmoji(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }

        for (int i = 0; i < str.length(); i++) {
            char codePoint = str.charAt(i);
            if (isEmojiCharacter(codePoint)) {
                return true;
            }
        }
        return false;
    }

    private static boolean isEmojiCharacter(char codePoint) {
        return !((codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }

    /**
     * 过滤emoji 或者 其他非文字类型的字符
     *
     * @param source
     * @return
     */
    public static String filterEmoji(String str) {

        if (!containsEmoji(str)) {
            return str;//如果不包含，直接返回
        } else {
            LogUtil.v("jj", "contain emoji expression");
        }
        //到这里铁定包含
        StringBuilder buf = null;
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char codePoint = str.charAt(i);
            if (!isEmojiCharacter(codePoint)) {
                if (buf == null) {
                    buf = new StringBuilder(str.length());
                }
                buf.append(codePoint);
            } else {

            }
        }

        if (buf == null) {
            return "";//如果全部为 emoji表情，则返回空字符串
        } else {
            return buf.toString();
        }

    }

}